package net.xdclass.service.impl;

import lombok.extern.slf4j.Slf4j;
import net.xdclass.component.MailService;
import net.xdclass.constant.CacheKey;
import net.xdclass.enums.BizCodeEnum;
import net.xdclass.enums.SendCodeEnum;
import net.xdclass.exception.BizException;
import net.xdclass.service.NotifyService;
import net.xdclass.util.CheckUtil;
import net.xdclass.util.CommonUtil;
import net.xdclass.util.JsonData;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * 通知服务实现类
 *
 * @author JiangZhou
 * @date 2023/4/29 15:00
 */
@Service
@Slf4j
public class NotifyServiceImpl implements NotifyService {

    @Resource
    private MailService mailService;

    @Resource
    private RedisTemplate redisTemplate;

    private final String SUBJECT = "欢迎注册JZ的小站！";

    private final String CONTENT = "您的以验证码是%s,有效期为60s,一定不要告诉其他人！";

    private final int CODE_EXPIRED = 1000 * 60;

    @Override
    public JsonData sendMail(SendCodeEnum sendCodeEnum, String to) {
        String cacheKey = String.format(CacheKey.CHECK_CODE_KEY, sendCodeEnum.name(), to);

        String cacheValue = (String) redisTemplate.opsForValue().get(cacheKey);

        //检查邮箱是否合法
        boolean isEmailCorrect = CheckUtil.isEmail(to);
        if (!isEmailCorrect) {
            throw new BizException(80001, "您的邮箱错误！");
        }
        //如果不为空，则判断是否60秒内重复发送
        if (StringUtils.isNotBlank(cacheValue)) {
            long ttl = Long.parseLong(cacheValue.split("_")[1]);
            //当前时间戳-验证码发送时间戳，如果小于60秒，则不给重复发送
            if (CommonUtil.getCurrentTimestamp() - ttl < 1000 * 60) {
                log.info("重复发送验证码,时间间隔:{} 秒", (CommonUtil.getCurrentTimestamp() - ttl) / 1000);
                return JsonData.buildResult(BizCodeEnum.CODE_LIMITED);
            }
        }

        //拼接验证码 2322_324243232424324
        String code = CommonUtil.getRandomCode(6);

        String value = code + "_" + CommonUtil.getCurrentTimestamp();

        redisTemplate.opsForValue().set(cacheKey, value, CODE_EXPIRED, TimeUnit.MILLISECONDS);

        //进行邮件发送
        mailService.sendMail(to, SUBJECT, String.format(CONTENT, code));
        return JsonData.buildSuccess();
    }

    @Override
    public boolean checkCode(SendCodeEnum sendCodeEnum, String to, String code) {
        String cacheKey = String.format(CacheKey.CHECK_CODE_KEY, sendCodeEnum.name(), to);
        String cacheValue = (String) redisTemplate.opsForValue().get(cacheKey);
        if (StringUtils.isNotBlank(cacheValue)) {
            String cacheCode = cacheValue.split("_")[0];
            if (StringUtils.equals(cacheCode, code)) {
                redisTemplate.delete(cacheKey);
                return true;
            }
        }
        return false;
    }
}
